package com.muyu.payment.controller;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.muyu.payment.config.AliPayConfig;
import com.muyu.common.core.domain.Result;
import com.muyu.payment.domain.RechargeOrder;
import com.muyu.payment.domain.resp.PaymentCallbackResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.muyu.payment.service.PaymentOrderService;
import com.muyu.payment.service.PaymentIndentService;
import com.muyu.payment.service.RechargeService;
import com.muyu.payment.domain.req.PaymentCallbackReq;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付API控制器
 * 
 * @author muyu
 */
@RestController
@RequestMapping({"/payment","/pay"})
@Slf4j
@CrossOrigin(origins = "*")
@Tag(name = "支付API", description = "支付相关接口")
public class ApiPayController {
    
    @Autowired
    private AliPayConfig aliPayConfig;

    @Autowired
    private PaymentOrderService paymentOrderService;

    @Autowired
    private PaymentIndentService paymentIndentService;

    @Autowired
    private RechargeService rechargeService;

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    /**
     * 简易内存表：记录已支付的业务订单号（out_trade_no）。
     * 说明：演示用途，生产环境应落库并保证幂等更新。
     */
    private static final ConcurrentHashMap<String, Boolean> PAID_ORDERS = new ConcurrentHashMap<>();

    @PostMapping(value = "/pay", consumes = "application/x-www-form-urlencoded")
    @Operation(summary = "支付")
    public Result<String> pay(@Parameter(description = "订单号", required = true) @RequestParam("orderNo") String orderNo,
                         @Parameter(description = "支付金额", required = true) @RequestParam("amount") String amount,
                         @Parameter(description = "订单标题") @RequestParam("subject") String subject,
                         @Parameter(description = "支付类型") @RequestParam(value = "payType", required = false) String payType) {
        try {
            // 已支付拦截（演示）：若内存表标记为已支付，则拒绝再次发起
            if (Boolean.TRUE.equals(PAID_ORDERS.get(orderNo))) {
                return Result.error("订单已支付，无法重复支付");
            }
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), "JSON", "UTF-8", aliPayConfig.getAlipayPublicKey(),
                    "RSA2");

            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());
            request.setReturnUrl(aliPayConfig.getReturnUrl());

            HashMap<String, Object> map = new HashMap<>();
            map.put("out_trade_no", orderNo);
            map.put("total_amount", amount);
            map.put("subject", subject);
            map.put("product_code", "FAST_INSTANT_TRADE_PAY");

            request.setBizContent(JSON.toJSONString(map));
            return Result.success(alipayClient.pageExecute(request).getBody());
        } catch (AlipayApiException e) {
            log.error("支付失败：{}", e.getMessage(), e);
            return Result.error("支付失败：" + e.getMessage());
        }
    }

    @GetMapping("/pay")
    @Operation(summary = "支付(GET)")
    public Result<String> payGet(@Parameter(description = "订单号", required = true) @RequestParam("orderNo") String orderNo,
                         @Parameter(description = "支付金额", required = true) @RequestParam("amount") String amount,
                         @Parameter(description = "订单标题") @RequestParam("subject") String subject,
                         @Parameter(description = "支付类型") @RequestParam(value = "payType", required = false) String payType) {
        return pay(orderNo, amount, subject, payType);
    }

    @GetMapping("/ping")
    public String ping() {
        log.info("payment ping");
        return "ok";
    }


    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "cloud-payment");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }

    @PostMapping("/notify")
    @Operation(summary = "支付宝异步回调")
    public String notify(HttpServletRequest request) {
        try {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, requestParams.get(name)[0]);
            }

            log.info("收到支付宝回调，参数：{}", params);

            boolean checkV1 = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
            log.info("支付宝回调签名验证结果：{}", checkV1);
            
            if (checkV1) {
                String tradeStatus = params.get("trade_status");
                String outTradeNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                
                log.info("解析回调参数 - 订单号：{}，交易号：{}，状态：{}", outTradeNo, tradeNo, tradeStatus);
                
                // 处理支付成功的情况
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    log.info("支付成功，订单号：{}，支付宝交易号：{}", outTradeNo, tradeNo);
                
                    // 根据订单号前缀判断订单类型
                    if (outTradeNo.startsWith("RC")) {
                        // 充值订单回调处理
                        try {
                            boolean success = rechargeService.handleRechargeCallback(outTradeNo, tradeNo, 1);
                            if (success) {
                                log.info("充值订单回调处理成功，订单号：{}", outTradeNo);
                                // 内存表也标记（兼容前端快速校验）
                                PAID_ORDERS.put(outTradeNo, true);
                                return "success";
                            } else {
                                log.error("充值订单回调处理失败，订单号：{}", outTradeNo);
                                return "fail";
                            }
                        } catch (Exception e) {
                            log.error("充值订单回调处理异常，订单号：{}", outTradeNo, e);
                            return "fail";
                        }
                    } else {
                        // 支付订单回调处理
                        try {
                            PaymentCallbackReq callbackReq = PaymentCallbackReq.builder()
                                    .orderNo(outTradeNo)
                                    .thirdTradeNo(tradeNo)
                                    .payChannel("alipay")
                                    .payAmount(new java.math.BigDecimal(params.get("total_amount")))
                                    .payTime(new java.util.Date())
                                    .payStatus("SUCCESS")
                                    .build();
                            
                            PaymentCallbackResp response = paymentIndentService.handlePaymentCallback(callbackReq);
                            if ("SUCCESS".equals(response.getResult())) {
                                log.info("支付订单回调处理成功，订单号：{}", outTradeNo);
                                // 内存表也标记（兼容前端快速校验）
                                PAID_ORDERS.put(outTradeNo, true);
                                return "success";
                            } else {
                                log.error("支付订单回调处理失败，订单号：{}，原因：{}", outTradeNo, response.getMessage());
                                return "fail";
                            }
                        } catch (Exception e) {
                            log.error("支付订单回调处理异常，订单号：{}", outTradeNo, e);
                            return "fail";
                        }
                    }
                } else if (tradeStatus == null) {
            log.warn("支付状态为空，订单号：{}，参数异常", outTradeNo);
                    if (outTradeNo != null && tradeNo != null) {
                        log.info("尝试处理状态为空的支付回调，订单号：{}", outTradeNo);
                        
                        // 根据订单号前缀判断订单类型
                        if (outTradeNo.startsWith("RC")) {
                            // 充值订单回调处理
                            try {
                                boolean success = rechargeService.handleRechargeCallback(outTradeNo, tradeNo, 1);
                                if (success) {
                                    log.info("状态为空的充值回调处理成功，订单号：{}", outTradeNo);
                                    // 内存表也标记（兼容前端快速校验）
                                    PAID_ORDERS.put(outTradeNo, true);
                                    return "success";
                                } else {
                                    log.error("状态为空的充值回调处理失败，订单号：{}", outTradeNo);
                                    return "fail";
                                }
                            } catch (Exception e) {
                                log.error("状态为空的充值回调处理异常，订单号：{}", outTradeNo, e);
                                return "fail";
                            }
                        } else {
                            // 支付订单回调处理
                            try {
                                PaymentCallbackReq callbackReq = PaymentCallbackReq.builder()
                                        .orderNo(outTradeNo)
                                        .thirdTradeNo(tradeNo)
                                        .payChannel("alipay")
                                        .payAmount(new java.math.BigDecimal(params.getOrDefault("total_amount", "0")))
                                        .payTime(new java.util.Date())
                                        .payStatus("SUCCESS")
                                        .build();
                                
                                PaymentCallbackResp response = paymentIndentService.handlePaymentCallback(callbackReq);
                                if ("SUCCESS".equals(response.getResult())) {
                                    log.info("状态为空的支付回调处理成功，订单号：{}", outTradeNo);
                                    // 内存表也标记（兼容前端快速校验）
                                    PAID_ORDERS.put(outTradeNo, true);
                                    return "success";
                                } else {
                                    log.error("状态为空的支付回调处理失败，订单号：{}，原因：{}", outTradeNo, response.getMessage());
                                    return "fail";
                                }
                            } catch (Exception e) {
                                log.error("状态为空的支付回调处理异常，订单号：{}", outTradeNo, e);
                                return "fail";
                            }
                        }
                    } else {
                        log.error("订单号或交易号为空，无法处理回调");
                        return "fail";
                    }
                } else {
                    log.info("支付未完成，订单号：{}，状态：{}", outTradeNo, tradeStatus);
                    return "fail";
                }
            } else {
                log.warn("支付宝回调签名验证失败");
                return "fail";
            }
        } catch (Exception e) {
            log.error("处理支付宝回调异常：{}", e.getMessage(), e);
            return "fail";
        }
    }

    @GetMapping("/return")
    @Operation(summary = "支付宝同步返回")
    public String returnUrl(HttpServletRequest request) {
        try {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, requestParams.get(name)[0]);
            }

            log.info("收到支付宝同步返回，参数：{}", params);

            boolean checkV1 = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
            log.info("支付宝同步返回签名验证结果：{}", checkV1);
            
            if (checkV1) {
                String tradeStatus = params.get("trade_status");
                String outTradeNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                
                log.info("解析同步返回参数 - 订单号：{}，交易号：{}，状态：{}", outTradeNo, tradeNo, tradeStatus);
                
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    log.info("支付成功（同步返回），订单号：{}，支付宝交易号：{}", outTradeNo, tradeNo);
                    
                    // 根据订单号前缀判断订单类型
                    if (outTradeNo.startsWith("RC")) {
                        // 充值订单回调处理
                        try {
                            boolean success = rechargeService.handleRechargeCallback(outTradeNo, tradeNo, 1);
                            if (success) {
                                log.info("充值订单回调处理成功（同步返回），订单号：{}", outTradeNo);
                                // 内存表也标记（兼容前端快速校验）
                                PAID_ORDERS.put(outTradeNo, true);
                            } else {
                                log.error("充值订单回调处理失败（同步返回），订单号：{}", outTradeNo);
                            }
                        } catch (Exception e) {
                            log.error("充值订单回调处理异常（同步返回），订单号：{}", outTradeNo, e);
                        }
                    } else {
                        // 支付订单回调处理
                        try {
                            PaymentCallbackReq callbackReq = PaymentCallbackReq.builder()
                                    .orderNo(outTradeNo)
                                    .thirdTradeNo(tradeNo)
                                    .payChannel("alipay")
                                    .payAmount(new java.math.BigDecimal(params.get("total_amount")))
                                    .payTime(new java.util.Date())
                                    .payStatus("SUCCESS")
                                    .build();
                            
                            PaymentCallbackResp response = paymentIndentService.handlePaymentCallback(callbackReq);
                            if ("SUCCESS".equals(response.getResult())) {
                                log.info("支付订单回调处理成功（同步返回），订单号：{}", outTradeNo);
                                // 内存表也标记（兼容前端快速校验）
                                PAID_ORDERS.put(outTradeNo, true);
                            } else {
                                log.error("支付订单回调处理失败（同步返回），订单号：{}，原因：{}", outTradeNo, response.getMessage());
                            }
                        } catch (Exception e) {
                            log.error("支付订单回调处理异常（同步返回），订单号：{}", outTradeNo, e);
                        }
                    }
                    return "<html><head><meta charset='UTF-8'><title>支付成功</title></head><body style='font-family: Arial, sans-serif; text-align: center; padding: 50px;'><div style='max-width: 500px; margin: 0 auto; background: #f8f9fa; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'><h1 style='color: #28a745; margin-bottom: 20px;'>✅ 支付成功！</h1><p style='font-size: 16px; margin-bottom: 20px;'>订单号：<strong>" + outTradeNo + "</strong></p><p style='color: #666; margin-bottom: 30px;'>感谢您的购买，正在为您跳转...</p><div style='background: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px;'><p style='margin: 0; font-size: 14px;'>页面将在 <span id='countdown' style='color: #007bff; font-weight: bold; font-size: 18px;'>10</span> 秒后自动跳转到支付成功页面</p></div><button onclick='goToOrders()' style='background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 16px;'>立即跳转</button></div><script>let count = 10; const timer = setInterval(() => { count--; document.getElementById('countdown').textContent = count; if (count <= 0) { clearInterval(timer); goToOrders(); } }, 1000); function goToOrders() { window.location.href = 'http://localhost:9090/#/pages/payment/success/index?orderNo=' + encodeURIComponent('" + outTradeNo + "') + '&total_amount=' + encodeURIComponent('" + params.get("total_amount") + "'); }</script></body></html>";
                } else if (tradeStatus == null) {
                    log.warn("同步返回支付状态为空，订单号：{}，参数异常", outTradeNo);
                    // 对于状态为空的情况，尝试处理为支付成功
                    if (outTradeNo != null && tradeNo != null) {
                        log.info("尝试处理状态为空的同步返回，订单号：{}", outTradeNo);
                        
                        // 根据订单号前缀判断订单类型
                        if (outTradeNo.startsWith("RC")) {
                            // 充值订单回调处理
                            try {
                                boolean success = rechargeService.handleRechargeCallback(outTradeNo, tradeNo, 1);
                                if (success) {
                                    log.info("状态为空的充值同步返回处理成功，订单号：{}", outTradeNo);
                                    // 内存表也标记（兼容前端快速校验）
                                    PAID_ORDERS.put(outTradeNo, true);
                                } else {
                                    log.error("状态为空的充值同步返回处理失败，订单号：{}", outTradeNo);
                                }
                            } catch (Exception e) {
                                log.error("状态为空的充值同步返回处理异常，订单号：{}", outTradeNo, e);
                            }
                        } else {
                            // 支付订单回调处理
                            try {
                                PaymentCallbackReq callbackReq = PaymentCallbackReq.builder()
                                        .orderNo(outTradeNo)
                                        .thirdTradeNo(tradeNo)
                                        .payChannel("alipay")
                                        .payAmount(new java.math.BigDecimal(params.getOrDefault("total_amount", "0")))
                                        .payTime(new java.util.Date())
                                        .payStatus("SUCCESS")
                                        .build();
                                
                                PaymentCallbackResp response = paymentIndentService.handlePaymentCallback(callbackReq);
                                if ("SUCCESS".equals(response.getResult())) {
                                    log.info("状态为空的支付同步返回处理成功，订单号：{}", outTradeNo);
                                    // 内存表也标记（兼容前端快速校验）
                                    PAID_ORDERS.put(outTradeNo, true);
                                } else {
                                    log.error("状态为空的支付同步返回处理失败，订单号：{}，原因：{}", outTradeNo, response.getMessage());
                                }
                            } catch (Exception e) {
                                log.error("状态为空的支付同步返回处理异常，订单号：{}", outTradeNo, e);
                            }
                        }
                        return "<html><head><meta charset='UTF-8'><title>支付成功</title></head><body style='font-family: Arial, sans-serif; text-align: center; padding: 50px;'><div style='max-width: 500px; margin: 0 auto; background: #f8f9fa; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'><h1 style='color: #28a745; margin-bottom: 20px;'>✅ 支付成功！</h1><p style='font-size: 16px; margin-bottom: 20px;'>订单号：<strong>" + outTradeNo + "</strong></p><p style='color: #666; margin-bottom: 30px;'>感谢您的购买，正在为您跳转...</p><div style='background: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px;'><p style='margin: 0; font-size: 14px;'>页面将在 <span id='countdown' style='color: #007bff; font-weight: bold; font-size: 18px;'>10</span> 秒后自动跳转到支付成功页面</p></div><button onclick='goToOrders()' style='background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 16px;'>立即跳转</button></div><script>let count = 10; const timer = setInterval(() => { count--; document.getElementById('countdown').textContent = count; if (count <= 0) { clearInterval(timer); goToOrders(); } }, 1000); function goToOrders() { window.location.href = 'http://localhost:9090/#/pages/payment/success/index?orderNo=' + encodeURIComponent('" + outTradeNo + "') + '&total_amount=' + encodeURIComponent('" + params.get("total_amount") + "'); }</script></body></html>";
                    } else {
                        log.error("同步返回订单号或交易号为空，无法处理");
                        return "<html><head><meta charset='UTF-8'><title>处理异常</title></head><body style='font-family: Arial, sans-serif; text-align: center; padding: 50px;'><div style='max-width: 500px; margin: 0 auto; background: #f8f9fa; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'><h1 style='color: #dc3545; margin-bottom: 20px;'>⚠️ 处理异常</h1><p style='color: #666; margin-bottom: 30px;'>订单号或交易号为空</p><button onclick='goToOrders()' style='background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 16px;'>查看支付结果</button></div><script>function goToOrders() { window.location.href = 'http://localhost:9090/#/pages/payment/success/index'; }</script></body></html>";
                    }
                } else {
                    log.info("支付未完成，订单号：{}，状态：{}", outTradeNo, tradeStatus);
                    return "<html><head><meta charset='UTF-8'><title>支付未完成</title></head><body style='font-family: Arial, sans-serif; text-align: center; padding: 50px;'><div style='max-width: 500px; margin: 0 auto; background: #f8f9fa; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'><h1 style='color: #dc3545; margin-bottom: 20px;'>❌ 支付未完成</h1><p style='font-size: 16px; margin-bottom: 20px;'>订单号：<strong>" + outTradeNo + "</strong></p><p style='color: #666; margin-bottom: 30px;'>状态：" + tradeStatus + "</p><button onclick='goToOrders()' style='background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 16px;'>查看支付结果</button></div><script>function goToOrders() { window.location.href = 'http://localhost:9090/#/pages/payment/success/index?orderNo=" + outTradeNo + "&total_amount=" + params.get("total_amount") + "'; }</script></body></html>";
                }
            } else {
                log.warn("支付宝同步返回签名验证失败");
                return "<html><head><meta charset='UTF-8'><title>签名验证失败</title></head><body style='font-family: Arial, sans-serif; text-align: center; padding: 50px;'><div style='max-width: 500px; margin: 0 auto; background: #f8f9fa; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'><h1 style='color: #dc3545; margin-bottom: 20px;'>⚠️ 签名验证失败</h1><p style='color: #666; margin-bottom: 30px;'>支付验证出现问题，请重试</p><button onclick='goToOrders()' style='background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 16px;'>查看支付结果</button></div><script>function goToOrders() { window.location.href = 'http://localhost:9090/#/pages/payment/success/index'; }</script></body></html>";
            }
        } catch (Exception e) {
            log.error("处理支付宝同步返回异常：{}", e.getMessage(), e);
            return "<html><head><meta charset='UTF-8'><title>处理异常</title></head><body style='font-family: Arial, sans-serif; text-align: center; padding: 50px;'><div style='max-width: 500px; margin: 0 auto; background: #f8f9fa; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'><h1 style='color: #dc3545; margin-bottom: 20px;'>⚠️ 处理异常</h1><p style='color: #666; margin-bottom: 30px;'>" + e.getMessage() + "</p><button onclick='goToOrders()' style='background: #007bff; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 16px;'>查看支付结果</button></div><script>function goToOrders() { window.location.href = 'http://localhost:9090/#/pages/payment/success/index'; }</script></body></html>";
        }
    }

    /**
     * 查询订单是否已支付
     * @param orderNo
     * @return
     */
    @GetMapping("/paid/status")
    @Operation(summary = "查询订单是否已支付（演示内存表）")
    public Result<Boolean> isPaid(@RequestParam("orderNo") String orderNo) {
        boolean status  = paymentOrderService.isPaid(orderNo);
        return Result.success(status);
    }

    /**
     * 查询充值订单是否已支付
     * @param orderNo
     * @return
     */
    @GetMapping("/recharge/paid/status")
    @Operation(summary = "查询充值订单是否已支付")
    public Result<Boolean> isRechargePaid(@RequestParam("orderNo") String orderNo) {
        try {
            // 先检查内存表
            if (PAID_ORDERS.containsKey(orderNo)) {
                return Result.success(true);
            }
            
            // 查询充值订单状态
            RechargeOrder rechargeOrder = rechargeService.getRechargeOrderByOrderNo(orderNo);
            if (rechargeOrder != null) {
                boolean isPaid = rechargeOrder.getOrderStatus() == 2; // 1表示已支付
                return Result.success(isPaid);
            }
            
            return Result.success(false);
        } catch (Exception e) {
            log.error("查询充值订单支付状态失败，订单号：{}", orderNo, e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 充值专用回调接口
     */
    @PostMapping("/recharge/notify")
    @Operation(summary = "充值支付宝异步回调")
    public String rechargeNotify(HttpServletRequest request) {
        try {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, requestParams.get(name)[0]);
            }

            log.info("收到充值支付宝回调，参数：{}", params);

            boolean checkV1 = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
            log.info("充值支付宝回调签名验证结果：{}", checkV1);
            
            if (checkV1) {
                String tradeStatus = params.get("trade_status");
                String outTradeNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                
                log.info("解析充值回调参数 - 订单号：{}，交易号：{}，状态：{}", outTradeNo, tradeNo, tradeStatus);
                
                // 处理支付成功的情况
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    log.info("充值支付成功，订单号：{}，支付宝交易号：{}", outTradeNo, tradeNo);
                
                    // 调用充值服务处理回调
                    try {
                        boolean success = rechargeService.handleRechargeCallback(outTradeNo, tradeNo, 1);
                        if (success) {
                            log.info("充值回调处理成功，订单号：{}", outTradeNo);
                            // 内存表也标记（兼容前端快速校验）
                            PAID_ORDERS.put(outTradeNo, true);
                            return "success";
                        } else {
                            log.error("充值回调处理失败，订单号：{}", outTradeNo);
                            return "fail";
                        }
                    } catch (Exception e) {
                        log.error("充值回调处理异常，订单号：{}", outTradeNo, e);
                        return "fail";
                    }
                } else if (tradeStatus == null) {
            log.warn("充值支付状态为空，订单号：{}，参数异常", outTradeNo);
                    if (outTradeNo != null && tradeNo != null) {
                        log.info("尝试处理状态为空的充值支付回调，订单号：{}", outTradeNo);
                        
                        try {
                            boolean success = rechargeService.handleRechargeCallback(outTradeNo, tradeNo, 1);
                            if (success) {
                                log.info("状态为空的充值回调处理成功，订单号：{}", outTradeNo);
                                // 内存表也标记（兼容前端快速校验）
                                PAID_ORDERS.put(outTradeNo, true);
                                return "success";
                            } else {
                                log.error("状态为空的充值回调处理失败，订单号：{}", outTradeNo);
                                return "fail";
                            }
                        } catch (Exception e) {
                            log.error("状态为空的充值回调处理异常，订单号：{}", outTradeNo, e);
                            return "fail";
                        }
                    } else {
                        log.error("充值订单号或交易号为空，无法处理回调");
                        return "fail";
                    }
                } else {
                    log.info("充值支付未完成，订单号：{}，状态：{}", outTradeNo, tradeStatus);
                    return "fail";
                }
            } else {
                log.warn("充值支付宝回调签名验证失败");
                return "fail";
            }
        } catch (Exception e) {
            log.error("处理充值支付宝回调异常：{}", e.getMessage(), e);
            return "fail";
        }
    }
}